'use strict';

const Koa = require('koa');

const router = require('koa-router')();//相当于  const fn_router=require('koa-router');  const router=fn_router();

const bodyParser=require('koa-bodyparser');

const app = new Koa();

app.use(async (ctx,next)=>
{
    console.log(`Process ${ctx.request.method} ${ctx.request.url}...`);
    await next();
});
router.get('/hello/:name',async(ctx,next)=>
{
    var name=ctx.params.name;
    ctx.response.body=`<h1> Hello ${name}!</h1>`;
});


router.get('/', async(ctx,next)=>
{
    ctx.response.body=`<h1>Index</h1>
        <form action="/signin" method="post">
            <p>Name: <input name="name" value="koa"></p>
            <p>Password: <input name="password" type="password"></p>
            <p><input type="submit" value="Submit"></p>
        </form>`;
});
router.post('/signin',async(ctx,next)=>
{
    var name=ctx.request.body.name||"";
    var password=ctx.request.body.password||"";
    console.log(`singin with name:${name},password:${password}`);
    if(name==='koa'&&password==='123456')
    {
        ctx.response.body=`<h1>welcome ${name}!</h1>`;
    }
    else
    {
        ctx.response.body=`<h1>Login failed</h1>
        <p><a href="/">try again</a></p>`;
    }
});



app.use(bodyParser());//添加后，能在post中反问body
app.use(router.routes());  //把router注册的响应方法添加进来


app.listen(3000);
console.log('app started at port 3000...');